//
//  SNForgetViewController.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/10.
//  Copyright © 2016年 stone. All rights reserved.
//

#import "SNForgetViewController.h"
#import "Masonry.h"
#import "NSDate+TimeStamp.h"
@interface SNForgetViewController ()
{
    NSTimer *_timer;
    NSInteger verificationTimeCount;
}

@property (weak, nonatomic) IBOutlet UIButton *submitButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *authcodeTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *affirmTextField;
//验证码按钮
@property (weak, nonatomic) IBOutlet UIButton *verCodeBtn;

/** time */
@property (nonatomic,copy) NSString * time;
/** captcha */
@property (nonatomic,copy) NSString * captcha;
/** phone */
@property (nonatomic,copy) NSString * phone;
@end

@implementation SNForgetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = HexRGB(0xF5F5F5);
    self.navigationItem.title = @"找回密码";
    // Do any additional setup after loading the view.
    [self.submitButton setBackgroundImage:[SNUtils imageWithColor:HexRGB(0x57A736)] forState:UIControlStateNormal];
    [self.submitButton setBackgroundImage:[SNUtils imageWithColor:HexRGB(0x9ACD8B)] forState:UIControlStateDisabled];
    
    self.submitButton.enabled = NO;
    [self addObserver];
    
    
}
- (void)textChange:(NSNotification *)notify
{
    //    NSLog(@"%@",notify);
    if (self.phoneTextField.text.length>0 &&
        self.authcodeTextField.text.length>0&&
        self.passwordTextField.text.length>0 &&
        self.affirmTextField.text.length>0) {
        
        self.submitButton.enabled = YES;
    }
    
}
- (void)addObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:nil];
    
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//判断手机号码格式是否正确
- (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

-(BOOL)checkPassWord
{
    if (self.passwordTextField.text.length < 6) {
        HUDNormal(@"请输入不小于6位数的密码");
    }else if(self.passwordTextField.text.length > 32){
        HUDNormal(@"密码长度超长");
    }
    //6-20位数字和字母组成
    NSString *regex = @"^(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([pred evaluateWithObject:self.passwordTextField.text]) {
        return YES ;
    }else
        return NO;
}




- (IBAction)authcodeButtonClicked:(UIButton *)sender {
    
    if (![self valiMobile:self.phoneTextField.text]) {
        HUDNormal(@"请检查您输入的手机号码!");
        return;
    };

    //    HUDLoading(@"");
    sender.enabled = NO;
    [self cheackCodeTime:0];
    
    if (![self checkPassWord]) {
        HUDNormal(@"密码必须是数字或字母组合");
        return;
    }
    
    
    NSDate * currentData = [NSDate new];
    NSString * time =  currentData.dateToString(@"yyyyMMddhhmmss");
    // 15874101378
    [[ZXHTTPManager sharedManager] getvfcodeWithTime:time phone:self.phoneTextField.text completed:^(NSDictionary *jsonDict, NSError *error) {
        logError;
        
        NSLog(@"%@",jsonDict);
        
        
        if (jsonDict[@"result"][0] != nil) {
            NSDictionary * result = jsonDict[@"result"][0];
            self.time = result[@"time"];
            self.captcha = result[@"captcha"];
        }

//        self.phone = result[@"phone"];
    }];
}


- (void)cheackCodeTime:(NSInteger)type
{
    if (type) {
        [self.verCodeBtn setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)verificationTimeCount] forState:UIControlStateNormal];
        
    }else{
        verificationTimeCount = 60;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countPass) userInfo:nil repeats:YES];
}

- (void)countPass
{
    verificationTimeCount --;
    if (verificationTimeCount <= 0) {
        [_timer invalidate];
        [self.verCodeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.verCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        self.verCodeBtn.enabled = YES;
        //        self.verCodeBtn.backgroundColor = GeneralBackColor;
        verificationTimeCount = 60;
    }else{
        [self.verCodeBtn setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)verificationTimeCount] forState:UIControlStateNormal];
        self.verCodeBtn.enabled = NO;
    }
}


- (IBAction)submitButtonClicked:(UIButton *)sender {
    
    if (![self.passwordTextField.text isEqualToString:self.affirmTextField.text]) {
        HUDNormal(@"两次输入的密码不一致,请检查");
        return;
    }
    
    if([self.passwordTextField.text isEqualToString:self.affirmTextField.text]){
        
        [[ZXHTTPManager sharedManager] chekcodeWithTime:self.time phone:self.phoneTextField.text vfcode:self.captcha completed:^(NSDictionary *jsonDict, NSError *error) {
            
            logError;
            
            NSLog(@"%@",jsonDict);
            // [SNProgressManager showToView:self.view message:jsonDict[@"message"] afterDelay:2];
            
            if ([jsonDict[@"status"] longValue] == 0) {
                //校验成功
                [self forgetpassword];
                
            }else{
                //失败
            }
        }];
    }else{
        [SNProgressManager showToView:self.view message:@"密码不一致,请重新输入" afterDelay:2];
    }
}
- (void)forgetpassword
{
    [[ZXHTTPManager sharedManager] forgetpasswordWithTime:self.time phone:self.phoneTextField.text captcha:self.captcha password:self.passwordTextField.text completed:^(NSDictionary *jsonDict, NSError *error) {
        
        logError;
        
        NSLog(@"%@",jsonDict);
        
        [SNProgressManager showToView:self.view message:jsonDict[@"message"] afterDelay:2];
        
        if ([jsonDict[@"status"] longValue] == 0) {
            //成功
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            //失败
        }
        
    }];
}
@end
